package com.zcs.android.app.jetpack.ui

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.zcs.android.app.jetpack.R
import com.zcs.android.app.jetpack.ui.home.HomeFragment
import com.zcs.android.lib.utils.LogUtils

class HomeActivity : AppCompatActivity() {
    lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.home_activity)

        val host: NavHostFragment = supportFragmentManager
            .findFragmentById(R.id.home_nav_host_fragment) as NavHostFragment? ?: return

        // Set up Nav Bar
        navController = host.navController
        setupBottomNavMenu(navController)
    }

    private fun setupBottomNavMenu(navController: NavController) {
        val bottomNav = findViewById<BottomNavigationView>(R.id.home_nav_view)
        bottomNav?.setupWithNavController(navController)
    }

    var lastBackTime: Long = 0

    @SuppressLint("RestrictedApi")
    override fun onBackPressed() {
        val currentDestination = navController.currentDestination

        LogUtils.w("displayName is ${currentDestination?.displayName}")
        LogUtils.w("label is ${currentDestination?.label}")

        if ("home_fragment" == currentDestination?.label) {
            if (System.currentTimeMillis() - lastBackTime > 2000) {
                lastBackTime = System.currentTimeMillis()
                Toast.makeText(this@HomeActivity, "再按一次退出Jetpack", Toast.LENGTH_SHORT).show()
                return
            }
        }

        super.onBackPressed()
    }
}
